package com.forezp.engin.executor;

import com.forezp.engin.datasource.DataSourceHolder;
import com.forezp.entity.TaskNode;
import com.forezp.service.TaskNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.script.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * springboot-jdbc-DefaultExecutor
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/3/16 17:15
 */
@Service
public class DefaultExecutor {


    @Autowired
    private TaskNodeService taskNodeService;

    @Autowired
    private DataSourceHolder dataSourceHolder;


    private ScriptEngine nashorn;

    {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        nashorn = scriptEngineManager.getEngineByName("nashorn");
    }


    public Object execute(Integer taskId) throws IOException, ScriptException, NoSuchMethodException {
        List<TaskNode> taskNodes = taskNodeService.findByTaskIdOrderByOrderDesc(taskId);
        AtomicReference<Object> frontStageResult = new AtomicReference();
        for (TaskNode taskNode : taskNodes) {
            List<Map<String, Object>> query = null;
            if (taskNode.getDataSource() != null) {
                query = dataSourceHolder.getSuitableJdbcTemplate(taskNode.getDataSource()).query(taskNode.getQuerySql(), new ColumnMapRowMapper());
            }
            Object eval = nashorn.eval(taskNode.getHandFunction());
            Invocable inv = (Invocable) nashorn;
            Object o = inv.invokeFunction("handle", frontStageResult.get(), query);
            frontStageResult.set(o);
        }
        return frontStageResult.get();
    }


}
